<template>
  <div>
    <!-- 添加或修改公告对话框 -->
    <el-dialog :title="title" :visible.sync="$parent.open" width="780px" append-to-body>
      <div class="center_dialog">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="位置名称" prop="placeName">
            <el-input v-model="form.placeName" placeholder="请输入位置名称" />
          </el-form-item>
          <el-form-item label="所属部门" prop="deptId">
            <el-select v-model="form.deptId" @change="SelectChange(form.deptId)" placeholder="请选择所属部门"
              style="width:100%">
              <el-option v-for="(dict, index) in systemList" :key="index" :label="dict.deptName" :value="dict.deptId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="负责人" prop="headId">
            <el-select v-model="form.headId" disabled placeholder="部门负责人" style="width:100%" class="bottomClear">
              <el-option v-for="(dict, index) in userList" :key="index" :label="dict.userName" :value="dict.userId">
              </el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="位置所属" prop="position">
            <el-select v-model="form.position" placeholder="请选择位置所属" style="width:100%">
              <el-option v-for="(dict, index) in ['室内位置', '室外位置']" :key="index" :label="dict" :value="index + ''">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="建筑物名称" prop="building" v-if="form.position === '0'">
            <el-select v-model="form.building" placeholder="请选择建筑物名称" style="width:100%">
              <el-option v-for="(dict, index) in dict.type.building_name" :key="index" :label="dict.label"
                :value="dict.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="位置坐标" prop="longitude">
            <el-button v-show="!bodyshow" type="primary" @click="() => bodyshow = !bodyshow" plain>打开位置</el-button>
            
            <div v-show="bodyshow" class="map_body" id="container"></div>

            <el-button v-show="bodyshow" class="map_buttom" icon="el-icon-check" @click="() => bodyshow = !bodyshow"
              circle></el-button>
            <el-input v-show="bodyshow" v-model="inputMap" id="input_id" class="map_input"
              @keyup.enter.native="handleSearch" placeholder="请输入搜索内容">
              <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
            </el-input>
            <br>
            经度:{{ form.longitude || '-' }} 纬度:{{ form.latitude || '-' }}
          </el-form-item> -->
          <el-form-item label="备注" prop="remark">
            <el-input type="textarea" v-model="form.remark" placeholder="请输入备注" />
          </el-form-item>
        </el-form>
      </div>
      <div align="center" slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="() => $parent.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { postplace, putUpdateplace, getuserlist, getsystemlist } from '@/api/equipment/equipment.js'
// import Upload from '@/components/upload/index.vue'
import AMapLoader from '@amap/amap-jsapi-loader';
import Assay from '@/assets/images/u9988.png';
//安全密钥
window._AMapSecurityConfig = {
  securityJsCode: '249c8810513321911bf1b25c975e075b',
}
export default {
  name: 'addLocation',
  props: ['title', 'rowObj'],
  dicts: ['building_name'],
  components: {
    // Upload
  },
  data () {
    return {
      bodyshow: false,
      inputMap: '',
      form: {
        "placeName": "", //位置名称
        "deptId": null, //部门ID
        "headId": null, //负责人ID
        // "position": "0",    //位置所属（0室内位置 1室外位置）
        // "building": "",    //建筑物名称 关联字典
        // "longitude": 114.031514, //经度
        // "latitude": 22.534035,  //纬度
        "remark": "" //备注
      },
      systemList: [],
      userList: [],
      rules: {
        placeName: { required: true, message: '必填', trigger: 'blur' },
        deptId: { required: true, message: '必填', trigger: 'blur' },
        headId: { required: true, message: '必填', trigger: 'blur' },
        // position: { required: true, message: '必填', trigger: 'blur' },
        // building: { required: true, message: '必填', trigger: 'blur' },
        // longitude: { required: true, message: '必填', trigger: 'blur' },
      }
    }
  },
  created () {
    this.getlist()
  },
  methods: {
    async getlist () {
      let params = await getsystemlist();//部门
      this.systemList = params.data
      if (this.title === '修改位置') {//修改进入
        this.form = { ...this.rowObj }
        this.SelectChange(this.form.deptId)
      }
      //DOM初始化完成进行地图初始化
      // this.initMap()
    },
    initMap () {
      const th = this
      AMapLoader.load({
        key: "d3c2d6765613d9728729a9c9afe9b78b",    // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0",      // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ["AMap.Scale", "AMap.ToolBar", "AMap.AutoComplete", "AMap.PlaceSearch", "AMap.ControlBar", "AMap.MouseTool"],       // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      }).then((AMap) => {
        this.map = new AMap.Map("container", {  //设置地图容器id
          viewMode: "2D",    //是否为3D地图模式
          zoom: 17,           //初始化地图级别
          center: this.title === '修改位置' ? [th.form.longitude, th.form.latitude] : [114.031514, 22.534035], //初始化地图中心点位置
          resizeEnable: true,
          mapStyle: 'amap://styles/blue', //设置地图的显示样式
        });
        var icon = new AMap.Icon({
          size: new AMap.Size(28, 28),    // 图标尺寸
          image: Assay,  // Icon的图像
          // imageOffset: new AMap.Pixel(0, -60),  // 图像相对展示区域的偏移量，适于雪碧图等
          imageSize: new AMap.Size(28, 28)   // 根据所设置的大小拉伸或压缩图片
        });
        var marker = new AMap.Marker({
          offset: new AMap.Pixel(-13, -26),
          position: new AMap.LngLat(th.form.longitude, th.form.latitude),
          icon: icon,
        });
        this.map.on('click', function (e) {
          th.form.longitude = e.lnglat.getLng()
          th.form.latitude = e.lnglat.getLat()
          marker.setPosition([e.lnglat.getLng(), e.lnglat.getLat()])
          th.map.panTo(marker.getPosition());
          console.log("经度", e.lnglat.getLng())
          console.log("纬度", e.lnglat.getLat())
        });
        let text = `<div style='background-color:rgb(26, 250, 41, 0);color:#feb02c;padding:5px 10px;border-radius:3px;'>经度:${th.form.longitude},纬度:${th.form.latitude}</div>`
        // 创建 infoWindow 实例	
        var infoWindow = new AMap.InfoWindow({
          content: text,  //传入 dom 对象，或者 html 字符串
          isCustom: true,  //使用自定义窗体
          anchor: 'top-center',
        });
        marker.on('mouseover', function (e) {//标记鼠标悬浮
          infoWindow.open(th.map, [th.form.longitude, th.form.latitude]);
        });
        marker.on('mouseout', function (e) {//标记鼠标离开
          infoWindow.close();
        });
        // AMap.plugin('AMap.AutoComplete', function () {
        // 实例化AutoComplete
        var autoOptions = {
          // 使用联想输入的input的id
          input: "input_id"
        }
        var autocomplete = new AMap.Autocomplete(autoOptions)
        // 无需再手动执行search方法，autoComplete会根据传入input对应的DOM动态触发search
        th.placeSearch = new AMap.PlaceSearch({
          map: th.map
        })
        autocomplete.on('select', (e) => {
          th.placeSearch.search(e.poi.name)
          th.form.longitude = e.poi.location.lng
          th.form.latitude = e.poi.location.lat
          marker.setPosition([e.poi.location.lng, e.poi.location.lat]) //更新标记点位置
          th.map.panTo(marker.getPosition());
        })
        // })
        this.map.addControl(new AMap.Scale());
        this.map.add(marker)
      }).catch(e => {
        console.log(e);
      })
    },
    handleSearch (e) {
      console.log(e);
      if (e.poi) {
        this.placeSearch.search(e.poi.name)
      } else {
        this.placeSearch.search(this.inputMap)
      }
    },
    async SelectChange (deptId) {
      this.systemList.map(item => {
        if (item.deptId === deptId) {
          this.userList.push({
            userName: item.leader,
            userId: item.leaderUserId
          })
          this.form.headId = item.leaderUserId
        }
      })
    },
    //提交
    submitForm () {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.title === '修改位置') {//修改
            let params = {
              ...this.form
            }
            putUpdateplace(params).then(res => {
              if (res.code === 200) {
                this.$message.success(res.msg)
                this.$parent.open = false
                this.$parent.getList()//重新查询列表
              }
            })
          } else {//新增
            let params = {
              ...this.form
            }
            postplace(params).then(res => {
              if (res.code === 200) {
                this.$message.success(res.msg)
                this.$parent.open = false
                this.$parent.handleUpdate()
              }
            })
          }
        }
      });
    },
  }
}
</script>

<style lang="scss" scoped>
.center_dialog {
  // text-align: center;
  width: 50%;
  margin: 0px auto;
}

#container {
  padding: 0px;
  margin: 0px;
  // width: 100%;
  // height: 250px;
}

.map_body {
  position: fixed;
  cursor: default;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: 1;
}

.map_buttom {
  position: fixed;
  top: 20px;
  right: 50px;
  z-index: 2;
}

.map_input {
  width: 280px;
  position: fixed;
  top: 20px;
  left: 50px;
  z-index: 2;
}
</style>
<style>
.amap-sug-result {
  z-index: 9999 !important;
}
</style>